import Store from "electron-store"
import axios from "axios"
import dayjs from "dayjs"
import md5 from "blueimp-md5"
import sleep from "sleep-promise"
import { ipcRenderer } from "electron";
// import { changeProgress } from '../index';

export class IP
{
	storage: Store<any>
	pool: any
	num: number
	support: string
	errorTime: number
	requestErrorTime: number
	key: string = ""
	user = "test2475"
	password = "913f5174b5"

	constructor(key:string, num:number = 8, support:string = "ayun") {
		this.storage = new Store()
		this.num = num
		this.support = support
		this.errorTime = 0
		this.requestErrorTime = 0
		this.key = key
	}

	async ayun(num:number):Promise<any> {
		// let url = process.env.NODE_ENV == 'development' ? 'obtain' : "https://api-ip.abuyun.com/obtain"
		let url = "https://api-ip.abuyun.com/obtain";
		let time = dayjs().unix()
		let sign = md5(this.user+time+this.password)
		let data = {
			license:this.user,
			time:time,
			sign:sign,
			cnt:num
		}
		console.log(url);
		try {
			let res = await this.request(url, data)
			return res
		} catch (error) {
			if (this.errorTime < 3) {
				this.errorTime++
				await sleep(3000)
				let res = await this.ayun(num)
				return res
			} else {
				return error
			}
		}
	}

	async request(url:string, data:any) {
		//return {"data":[{"code":0,"success":true,"msg":"0","data":[{"ip":"49.68.68.197","port":33220,"expire_time":"2017-06-20 20:40:24","city":"徐州市","isp":"电信"}, {"ip":"121.236.238.89","port":33502,"expire_time":"2017-06-20 20:42:15","city":"苏州市","isp":"电信"}]}]}
		return axios({
			url: url,
			params: data,
			method: "GET"
		});
	}

	async one():Promise<any> {
		return this.getIP()
	}



	async getIP():Promise<any> {
		//this.storage.set("pool", [])
		// console.log(this.storage.get(this.key + "_pool", []))
		if (
			!this.storage.has(this.key + "_pool") ||
			this.storage.get(this.key + "_pool", []).length == 0
		) {
			let res = ipcRenderer.sendSync('refresh', this.key)
			this.storage.set(this.key + "_pool", JSON.parse(res))
		}
		this.pool = this.storage.get(this.key + "_pool")
		console.log("当前 ip 池")
		console.log(this.pool)
		let rand = Math.round(Math.random() * this.pool.length)
		let res = this.pool[rand]
		//this.storage.set("pool", this.pool)
		//console.log("num:" + rand + "\nip:" + res)
		return res
	}

	async refresh():Promise<any> {
		let res:any = await eval(`this.${this.support}(${this.num})`)
		console.log("ipResult",res);
		res = res.data
		if (res.code == 0) {
			//this.storage.set("pool", ['218.75.158.156:16231', '218.75.158.159:24493', '218.75.158.150:12170', '218.75.158.184:12161'])
			this.storage.set(this.key + "_pool", res.proxies)
			// ("ip", res.left / 100)
			this.storage.set("ipLeft", res.left);
			// changeProgress("getLinkProcess", res.left);
			console.log("ip 剩余量：" + res.left)
		} else {
			if (res.left == 0) {
				console.log("ip 用完了，你在试你🐎呢，辉总快充钱")
			}
			if (res.code == 407) {
				console.log("ip 可能过期了，我再尝试一下")
				if (this.requestErrorTime++ < 3)
					await this.refresh()
				return
			}
			console.log(res)
		}
	}

	async addWhite(ip:string) {
		let whiteUrl = "https://api-ip.abuyun.com/whitelist/add"
		let time = dayjs().unix()
		let sign = md5(this.user + time + this.password)
		let data = {
			license: this.user,
			time: time,
			ip: ip,
			sign: sign
		}
		let res = await this.request(whiteUrl, data)

		if (res.data.code == 0) {
			return true;
		} else {
			return false;
		}
	}
}